﻿using System;
using System.Windows.Forms;
using Application = System.Windows.Forms.Application;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;

namespace Связь_с_БД
{
    class PrintDocumentMainCertificate
    {
       
        public PrintDocumentMainCertificate(DataGridViewRow dataGridViewRow)
        {
            _dataGridViewRow = dataGridViewRow;
            _mainCertificationReplace = new string[13];
        }

        private readonly string filePath = @"\PatternDocuments\spravka.docx";
        public bool IsClosed;                         

        private readonly string[] _mainCertification = {
                                                           "{              currentDate              }",
                                                           "{ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff}",
                                                           "{numberCourse}",
                                                           "{faculty}",
                                                           "{codeDirection}",
                                                           "{nameDirection}",
                                                           "{codeProphyle}",
                                                           "{nameProphyle}",
                                                           "{group}",
                                                           "{             startDate             }",
                                                           "{             endDate             }",
                                                           "{numberOrderOn}",
                                                           "{          dateOrder         }"
                                                       };
        private string[] _mainCertificationReplace;

        private DataGridViewRow _dataGridViewRow;

        private void SetMainCertificationValues(DataGridViewRow dgvr)
        {
            _mainCertificationReplace[0] = InsertTextInCenter(MakeFormatDate(DateTime.Today.ToShortDateString()),
                                                              _mainCertification[0]);
            _mainCertificationReplace[1] = InsertTextInCenter(dgvr.Cells[27].Value.ToString(),_mainCertification[1]);
            _mainCertificationReplace[2] = InsertTextInCenter(GetNumberCourse(dgvr.Cells[22].Value.ToString()),
                                                              _mainCertification[2]);
            _mainCertificationReplace[3] = InsertTextInCenter("ЭОиМ", _mainCertification[3]);
            _mainCertificationReplace[4] = InsertTextInCenter(dgvr.Cells[13].Value.ToString(),_mainCertification[4]);
            _mainCertificationReplace[5] = dgvr.Cells[14].Value.ToString();
            _mainCertificationReplace[6] = InsertTextInCenter(dgvr.Cells[16].Value.ToString(), _mainCertification[6]);
            _mainCertificationReplace[7] = dgvr.Cells[15].Value.ToString();
            _mainCertificationReplace[8] = InsertTextInCenter(dgvr.Cells[22].Value.ToString(), _mainCertification[8]);
            _mainCertificationReplace[9] = InsertTextInCenter(MakeStartDate(dgvr.Cells[66].Value.ToString()), _mainCertification[9]);
            _mainCertificationReplace[10] = InsertTextInCenter(MakeEndDate(dgvr.Cells[66].Value.ToString()), _mainCertification[10]); 
            _mainCertificationReplace[11] = InsertTextInCenter(GetNumberOrder(dgvr.Cells[67].Value.ToString()),_mainCertification[11]);
            _mainCertificationReplace[12] = InsertTextInCenter(MakeFormatDate(GetDateOrder(dgvr.Cells[67].Value.ToString(), dgvr.Cells[66].Value.ToString())),_mainCertification[12]);
        }

        private void ReplaceText(string text, string replaceText, Document worddocument, Word.Application wordapp)
        {
            Object start = 0;
            Object end = worddocument.Characters.Count;
            Word.Range wordrange = worddocument.Range(ref start, ref end);
            wordrange.TextRetrievalMode.IncludeHiddenText = false;
            wordrange.TextRetrievalMode.IncludeFieldCodes = false;
            //MessageBox.Show(wordrange.Text);

            int beginphrase = 0;
            beginphrase = wordrange.Text.IndexOf(text);
            start = beginphrase;
            end = beginphrase + text.Length;
            wordrange = worddocument.Range(ref start, ref end);
            //MessageBox.Show(wordrange.Text + " Найденный текст начинается с позиции: "
                                      // + Convert.ToString(beginphrase));
            object unit;
            object count;
            object extend;
            //ставим курсор в начало документа
            unit = Word.WdUnits.wdStory;
            extend = Word.WdMovementType.wdMove;
            wordapp.Selection.HomeKey(ref unit, ref extend);

            
            //переходим к началу нужной фразы
            unit = Word.WdUnits.wdCharacter;
            extend = Word.WdMovementType.wdMove;
            count = beginphrase;
            wordapp.Selection.MoveRight(ref unit, ref count, ref extend);

            //выделяем это слово
            unit = Word.WdUnits.wdCharacter;
            count = text.Length;
            extend = Word.WdMovementType.wdExtend;
            wordapp.Selection.MoveRight(ref unit, ref count, ref extend);

            wordapp.Options.Overtype = false;
            wordapp.Selection.Font.Name = @"Times New Roman";
            wordapp.Selection.Font.Size = 11;
            wordapp.Selection.Font.Underline = WdUnderline.wdUnderlineSingle;
            wordapp.Selection.Font.Color = WdColor.wdColorBlack;
            wordapp.Selection.TypeText(replaceText);
        }

        private string GetNumberCourse(string str)
        {
            string result;
            int index = str.IndexOf("-");
            index++;
            result = str.Substring(index, 1);
            return result;
        }

        private string GetNumberOrder(string str)
        {
            string result = string.Empty;
            int pos = str.IndexOf(" ");
            char[] mas = str.ToCharArray();
            for (int i = 0; i <= pos; i++)
                result += mas[i];
            return result;
        }

        private string GetDateOrder(string str, string year)
        {
            string result = string.Empty;
            int pos = str.IndexOf("от");
            pos = pos + 3;
            char[] mas = str.ToCharArray();
            char[] mas2 = year.ToCharArray();
            for (int i = pos; i < pos+5; i++) result += mas[i];
            for (int i = 5; i < 10; i++) result += mas2[i];    
            return result;
        }

        private string InsertTextInCenter(string str, string sourceString)
        {
            string result = string.Empty;
            if (str.Length > sourceString.Length)
                return null;
            if (str.Length == sourceString.Length)
                return str;
            
            double w = str.Length/2+1;
            double centerPositionStr = Math.Truncate(w);
            int cenPosStr = Convert.ToInt32(centerPositionStr);

            double ww = sourceString.Length/2+1;
            double centerPositionSource = Math.Truncate(ww);
            int cenPosSource = Convert.ToInt32(centerPositionSource);
            
            int res = cenPosSource - cenPosStr;
            
            int j = 0;
            for(int i=0;i<sourceString.Length;i++)
            {
                if( (i<=res) || i>(res+str.Length) ) result += " ";
                else
                {
                    result += str[j];
                    j++;
                }
            }
            return result;
        }

        private string MakeFormatDate(string date)
        {
            string result = string.Empty;
            char[] mas = date.ToCharArray();
            result += "\"";
            result += mas[0];
            result += mas[1];
            result += "\"";
            result += " ";
            result += " ";
            result += " ";
            result += mas[3];
            result += mas[4];
            result += " ";
            result += " ";
            result += " ";
            result += mas[6];
            result += mas[7];
            result += mas[8];
            result += mas[9];
            return result;
        }

        private string MakeStartDate(string date)
        {
            string result = string.Empty;
            char[] mas = date.ToCharArray();
            result += "\"";
            result += '0';
            result += '1';
            result += "\"";
            result += " ";
            result += " ";
            result += " ";
            result += '0';
            result += '9';
            result += " ";
            result += " ";
            result += " ";
            result += mas[6];
            result += mas[7];
            result += mas[8];
            result += mas[9];
            return result;
        }

        private string MakeEndDate(string date)
        {
            string result = string.Empty;
            string tmp = string.Empty;
            char[] mas = date.ToCharArray();
            result += "\"";
            result += '3';
            result += '0';
            result += "\"";
            result += " ";
            result += " ";
            result += " ";
            result += '0';
            result += '6';
            result += " ";
            result += " ";
            result += " ";
            result += mas[6];
            result += mas[7];
            tmp += mas[8].ToString() + mas[9].ToString();
            int numb = Convert.ToInt32(tmp) + 2;
            result += numb.ToString();
            return result;
        }

        public void InsertInDocument()
        {
            var wordapp = new Word.Application();
            wordapp.DocumentBeforeClose += WordappDocumentBeforeClose;
            string FilePath = Application.StartupPath + filePath;
            try
            {
                var worddoc = wordapp.Documents.Open(FilePath);
                SetMainCertificationValues(_dataGridViewRow);
                for (int i = 0; i < _mainCertificationReplace.Length; i++)
                    ReplaceText(_mainCertification[i], _mainCertificationReplace[i], worddoc, wordapp);

                object nameFormat =
                    WdSaveFormat.wdFormatDocumentDefault;
                worddoc.SaveAs(Application.StartupPath + "\\okok", nameFormat);
                wordapp.Visible = true;
                IsClosed = false;
            }
            catch (Exception ex)
            {
                 MessageBox.Show(ex.ToString());
                 wordapp.Quit();
            }
        }

        void WordappDocumentBeforeClose(Document doc, ref bool cancel)
        {
            IsClosed = true;
        }
    }
}